package com.axx.android.home.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseLazyFragment;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.activity.UserAdapter;
import com.axx.android.home.model.User;
import com.axx.android.home.model.UserList;
import com.axx.android.letter.activity.LetterDetailActivity;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.message.activity.MessageContractActivity;
import com.axx.android.profile.message.activity.MessageLetterAdapter;
import com.axx.android.profile.message.model.MessageLetter;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.media.CamcorderProfile.get;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserListFragment extends BaseLazyFragment implements AMapLocationListener {


    @Bind(R.id.vs_error)
    ViewStub mVsError;
    @Bind(R.id.rv_list)
    RecyclerView mRvList;
    @Bind(R.id.refresh_view)
    SJRefreshView mRefreshView;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private int pageNum = 15;
    private int curPage = 1;

    private UserAdapter userAdapter;
    private List<UserList.UserListBean> listBeen = new ArrayList<>();
    private View viewError;

    private  double curLong;
    private double curLat;

    public UserListFragment() {
        // Required empty public constructor
    }


    public static UserListFragment newInstance() {

        Bundle args = new Bundle();

        UserListFragment fragment = new UserListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_user_list;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        initAdapter();
        mRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchUser();
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        initLocation();
    }

    private void initAdapter() {
        userAdapter = new UserAdapter(R.layout.view_item_home_user, listBeen);
        mRvList.setAdapter(userAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        userAdapter.setLoadMoreView(new SimpleLoadMoreView());
        userAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchUser();
            }
        }, mRvList);
        //mRvList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).margin(40,40).build());
        userAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UserList.UserListBean userListBean = userAdapter.getData().get(position);
                String jsonString = GsonUtils.toJson(userListBean);
                try {
                    User.UserListBean userListBean1 = GsonUtils.fromJson(jsonString, new TypeToken<User.UserListBean>() {
                    });
                    Intent intent = new Intent(getActivity(), RecipientActivity.class);
                    intent.putExtra("model", userListBean1);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void initLocation() {
        if (LetterApp.curLocation == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mLocationOption = new AMapLocationClientOption();
            mlocationClient.setLocationListener(this);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        } else {
            refresh();
        }

    }

    private void refresh() {
        mRefreshView.post(new Runnable() {
            @Override
            public void run() {
                mRefreshView.setRefreshing(true);
                fetchUser();
            }
        });
    }

    @Subscribe
    public void onLocationEvent(LatLng latLng){
        curLong = latLng.longitude;
        curLat = latLng.latitude;
        refresh();
    }

    private void fetchUser() {
        Map<String, String> string = new HashMap<>();
        string.put("nowpage", curPage+"");
        string.put("pagenum", pageNum+"");

        string.put("userLongitude", String.valueOf(LetterApp.curLocation.getLongitude()));
        string.put("userLatitude", String.valueOf(LetterApp.curLocation.getLatitude()));
        string.put("longitude", curLong + "");
        string.put("latitude", curLat+"");

        HttpUtils.post(Constants.Url.User.USER_RECENT_LIST, string, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<UserList> userListBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<UserList>>() {
                    });
                    if (userListBaseModel.isSuccess()) {
                        showSuccess(userListBaseModel.data.getUserList());
                    } else {
                        showToast(userListBaseModel.message);
                    }
                } catch (JSONException e) {
                    mRefreshView.setRefreshing(false);
                    showErrorView();
                }
            }

            @Override
            public void onError() {
                mRefreshView.setRefreshing(false);
                showErrorView();
            }
        });
    }

    private void showErrorView() {
        if (viewError == null) {
            viewError = mVsError.inflate();
            viewError.findViewById(R.id.btn_retry).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    viewError.setVisibility(View.GONE);
                    refresh();
                }
            });
        } else {
            viewError.setVisibility(View.VISIBLE);
        }
    }

    private void showSuccess(List<UserList.UserListBean> userList) {
        mRefreshView.setRefreshing(false);
        if (viewError != null) {
            viewError.setVisibility(View.GONE);
        }
        if (curPage == 1) {
            userAdapter.setNewData(userList);
            userAdapter.setEmptyView(R.layout.view_default_emtpy, mRvList);
            userAdapter.disableLoadMoreIfNotFullPage(mRvList);
        } else {
            int loadCount = userList.size();
            userAdapter.addData(userList);
            if (loadCount < pageNum) {
                userAdapter.loadMoreEnd();
            } else {
                userAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        LetterApp.curLocation = aMapLocation;
        curLong = aMapLocation.getLongitude();
        curLat = aMapLocation.getLatitude();
        refresh();
    }
}
